package org.iteam.xlz.core.service.user;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.UUID;

import org.iteam.core.utils.DateUtil;
import org.iteam.core.utils.SqlBuilder;
import org.iteam.db.BaseService;
import org.iteam.xlz.core.entity.user.UserInfo;
import org.iteam.xlz.core.entity.user.UserRelationRecord;

public class UserRelationRecordService extends BaseService<UserRelationRecord>{
	private static UserRelationRecordService instance;
	
	private UserRelationRecordService(){}
	
	public static UserRelationRecordService getInstance(){
		if(null==instance){
			instance=new UserRelationRecordService();
		}
		return instance;
	}
	
	public boolean relate(UserRelationRecord model){
		Connection con=null;
		try {
			con=super.getConnection(false);
			SqlBuilder sql=SqlBuilder.createInsert("userrelationrecord");
			sql.addField("urrid",UUID.randomUUID().toString().replace("-","").toUpperCase());
			sql.addField("oid",model.getOid());
			sql.addField("superioruid",model.getSuperioruid());
			sql.addField("subordinateuid",model.getSubordinateuid());
			sql.addField("royaltyrate",model.getRoyaltyrate());
			sql.addField("amount",model.getAmount());
			sql.addField("createtime",DateUtil.currentTime());
			int i=super.updates(con,sql.getSql(),sql.getParams());
			
			UserInfo user=super.show(UserInfo.class,"select * from userinfo where uid=?",model.getSuperioruid());
			
			SqlBuilder sql2=SqlBuilder.createInsert("logaccount");
			sql2.addField("laid",UUID.randomUUID().toString().replace("-","").toUpperCase());
			sql2.addField("uid",user.getUid());
			sql2.addField("amount",model.getAmount());
			sql2.addFieldSql("items","金矿返现");
			sql2.addField("logtype",1);
			sql2.addField("createtime",DateUtil.currentTime());
			int j=super.updates(con,sql2.getSql(),sql2.getParams());
			
			BigDecimal money=new BigDecimal(user.getDaole());
			BigDecimal amount=new BigDecimal(model.getAmount());
			money=money.add(amount);
			money=money.setScale(2,BigDecimal.ROUND_HALF_UP);
			SqlBuilder usql=SqlBuilder.createUpdate("userinfo");
			usql.addField("daole",money.toString());
			usql.addWhere("uid",user.getUid());
			usql.addWhere("daole",user.getDaole());
			
			int k=super.updates(con,usql.getSql(),usql.getParams());
			if(i==1&&j==1&&k==1){
				super.commit(con);
				return true;
			}else{
				super.rollback(con);
				return false;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				super.rollback(con);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
		return false;
	}
}
